//
//  MineDataViewController.m
//  Bees
//
//  Created by NowYouCanSee on 2019/1/3.
//  Copyright © 2019 xiaohan. All rights reserved.
//

#import "MineDataViewController.h"
#import "MineCustomImageVItem.h"
#import "TZImagePickerController.h"
#import "UpLoadImageTool.h"
#import "UserServer.h"
#import "AccountSafetyViewController.h"
#import "MineDataChangeViewController.h"
#import "TZImageManager.h"

@interface MineDataViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate>
@property (nonatomic,strong) UserServer*userServer;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

@end

@implementation MineDataViewController
- (instancetype)init{
    if (self==[super init]) {
        self = [super initWithStyle:UITableViewStylePlain];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    LMJWordArrowItem*item = (LMJWordArrowItem*)[[self.sections firstObject].items objectAtIndex:1];
    item.subTitle = kCurUser.nickname;
    [self.tableView reloadData];
}

- (void)setupUI{
    self.title = XLocalized(@"我的Bees");
    MineCustomImageVItem *item0 = [MineCustomImageVItem new];
    item0.imageUrl = kCurUser.headimgurl;
    item0.defaultImg= kDefaultPortraitImage;
    item0.cellHeight= 70.0f;
    kWeakSelf(self);
    kWeakSelf(item0);
    item0.itemOperation = ^(NSIndexPath *indexPath) {
        [LEEAlert actionsheet].config
        .LeeAction(XLocalized(@"拍照"), ^{
            [weakself takePhoto];
        })
        .LeeAction(XLocalized(@"相册"), ^{
            TZImagePickerController *picker = [TZImagePickerController new];
            picker.maxImagesCount=1;
            picker.showSelectBtn = NO;
            picker.allowCrop = YES;
            picker.cropRect = CGRectMake(0, (kScreenHeight-kScreenWidth)*.5, kScreenWidth, kScreenWidth);
            picker.allowPickingVideo = NO;
            picker.didFinishPickingPhotosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                UIImage *icon = [photos firstObject];
                [MBProgressHUD showLoadTitile:@"" ToView:weakself.view];
                [UpLoadImageTool uploadImage:icon size:CGSizeMake(200, 200) complete:^(NSString * _Nonnull imageUrl, NSString * _Nonnull errorMsg) {
                    if (!errorMsg) {
                        weakself.userServer.action = @"headimgurl";
                        weakself.userServer.value = imageUrl;
                        [weakself.userServer saveAccountComplete:^(BOOL success, NSString * _Nonnull msg) {
                            [MBProgressHUD hideHUDForView:weakself.view];
                            if (success) {
                                kCurUser.headimgurl = imageUrl;
                                [kUserManager saveUserInfo];
                                weakitem0.imageUrl = kCurUser.headimgurl;
                                [weakself.tableView reloadData];
                            }else{
                                [weakself.view makeToast:errorMsg];
                            }
                        }];
                        
                    }else{
                        [weakself.view makeToast:errorMsg];
                    }
                }];
            };
            [weakself.navigationController presentViewController:picker animated:YES completion:nil];
        })
        .LeeCancelAction(@"取消", ^{
            // 点击事件Block
        })
        .LeeShow();
    };
    
    LMJWordArrowItem *item1 = [LMJWordArrowItem itemWithTitle:XLocalized(@"名称") subTitle: kCurUser.nickname];
    item1.subTitleColor = UIColorHex(#999999);
    item1.itemOperation = ^(NSIndexPath *indexPath) {
        MineDataChangeViewController *vc = [[MineDataChangeViewController alloc]initWithChangeType:ChangeDataUserName];
        [weakself.navigationController pushViewController:vc animated:YES];
    };
    LMJWordItem *item2 = [LMJWordItem itemWithTitle:XLocalized(@"Bees账号") subTitle: kCurUser.account];
    item2.subTitleColor = UIColorHex(#999999);
    LMJWordArrowItem *item3 = [LMJWordArrowItem itemWithTitle:XLocalized(@"账户安全") subTitle: @""];
    item3.destVc = AccountSafetyViewController.class;
    
    LMJItemSection *section = [LMJItemSection sectionWithItems:@[item0,item1,item2,item3] andHeaderTitle:nil footerTitle:nil];
    [self.sections addObject:section];
    self.tableView.tableFooterView = [UIView new];
}

#pragma mark - UIImagePickerController

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
   
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        if(kiOS8Later) {
            _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
//            _imagePickerVc.mediaTypes = @[(NSString*)kUTTypeImage];
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    [tzImagePickerVc showProgressHUD];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        // save photo and get asset / 保存图片，获取到asset
        kWeakSelf(self);
        [[TZImageManager manager] savePhotoWithImage:image location:nil completion:^(PHAsset *asset, NSError *error){
            [tzImagePickerVc hideProgressHUD];
            if (error) {
                NSLog(@"图片保存失败 %@",error);
            } else {
                TZAssetModel *assetModel = [[TZImageManager manager] createModelWithAsset:asset];
                    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initCropTypeWithAsset:assetModel.asset photo:image completion:^(UIImage *cropImage, id asset) {
                        [MBProgressHUD showLoadTitile:@"" ToView:weakself.view];
                        [UpLoadImageTool uploadImage:cropImage size:CGSizeMake(200, 200) complete:^(NSString * _Nonnull imageUrl, NSString * _Nonnull errorMsg) {
                            if (!errorMsg) {
                                weakself.userServer.action = @"headimgurl";
                                weakself.userServer.value = imageUrl;
                                [weakself.userServer saveAccountComplete:^(BOOL success, NSString * _Nonnull msg) {
                                    [MBProgressHUD hideHUDForView:weakself.view];
                                    if (success) {
                                        kCurUser.headimgurl = imageUrl;
                                        [kUserManager saveUserInfo];
                                        MineCustomImageVItem*item = (MineCustomImageVItem*)[self.sections[0].items objectAtIndex:0];
                                        item.imageUrl = kCurUser.headimgurl;
                                        [weakself.tableView reloadData];
                                    }else{
                                        [weakself.view makeToast:errorMsg];
                                    }
                                }];
                                
                            }else{
                                [weakself.view makeToast:errorMsg];
                            }
                        }];
                    }];
                    imagePicker.allowCrop = YES;
                    imagePicker.cropRect = CGRectMake(0, (kScreenHeight-kScreenWidth)*.5, kScreenWidth, kScreenWidth);
                    imagePicker.allowPickingVideo = NO;
                    imagePicker.allowPickingImage = YES;
                    [self presentViewController:imagePicker animated:YES completion:nil];
            }
        }];
    }
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9.0, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}


#pragma mark - getter

- (UserServer*)userServer{
    if (!_userServer) {
        _userServer = [UserServer new];
    }
    return _userServer;
}

@end
